package com.contract.management;

import java.io.File;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.ApplicationArguments;
import org.springframework.boot.ApplicationRunner;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.context.embedded.ConfigurableEmbeddedServletContainer;
import org.springframework.boot.context.embedded.EmbeddedServletContainerCustomizer;
import org.springframework.boot.web.client.RestTemplateBuilder;
import org.springframework.boot.web.servlet.ErrorPage;
import org.springframework.boot.web.servlet.ServletRegistrationBean;
import org.springframework.context.annotation.Bean;
import org.springframework.http.HttpStatus;
import org.springframework.web.client.RestTemplate;
import org.thymeleaf.exceptions.TemplateInputException;


@SpringBootApplication
public class ManagementApplication implements ApplicationRunner {
	
	private static final Logger log = LoggerFactory.getLogger(ManagementApplication.class);
	
	@Value("${office.basepath}")
	private String basePath;
	
	public static void main(String[] args) {
		SpringApplication.run(ManagementApplication.class, args);
	}
	
	@Bean
	public ServletRegistrationBean poServletRegistrationBean() {
		com.zhuozhengsoft.pageoffice.poserver.Server server = new com.zhuozhengsoft.pageoffice.poserver.Server();
		//设置PageOffice注册成功后,license.lic文件存放的目录
		server.setSysPath(basePath + "/system");
		ServletRegistrationBean srb = new ServletRegistrationBean(server);
		srb.addUrlMappings("/poserver.zz");
		srb.addUrlMappings("/pageoffice.js");
		srb.addUrlMappings("/pobstyle.css");
		srb.addUrlMappings("/sealsetup.exe");
		srb.addUrlMappings("/posetup.exe");
		return srb;
	}
	
	@Bean
	public ServletRegistrationBean sealServletRegistrationBean() {
		com.zhuozhengsoft.pageoffice.poserver.AdminSeal seal = new com.zhuozhengsoft.pageoffice.poserver.AdminSeal();
		seal.setAdminPassword("111111");
		//设置印章数据库文件poseal.db的存放目录
		seal.setSysPath(basePath + "/system");
		ServletRegistrationBean srb = new ServletRegistrationBean(seal);
		srb.addUrlMappings("/adminseal.zz");
		srb.addUrlMappings("/sealimage.zz");
		srb.addUrlMappings("/loginseal.zz");
		return srb;
	}

	@Override
	public void run(ApplicationArguments args) throws Exception {
		String[] paths = new String[] {"system", "templates", "contracts", "uploads", "temp"};
		for (String path : paths) {
			File f = new File(basePath, path);
			if(!f.exists()) {
				log.error("directory '{}' doesn't exist", f.getAbsolutePath());
				System.exit(-1);
			}
		}
		log.info("directory check success");
	}
	
	@Bean
	public RestTemplate restTemplate() {
	    RestTemplateBuilder restTemplateBuilder = new RestTemplateBuilder();
	    return restTemplateBuilder.build();
	}
}
